(function($){
	$.fn.extend({
		// defaultTabData: [{
		// 	 id:"home",
		//   name:"首页",
		//   url:"",
		//   active: true
		// }],
		// className:""
		// onAllTabClosed:function(){}
		// $parentBody:$("xxx"),
		// iframeHeight:"100%"
		// onSwitch:function(){}
		// style:'default' 
		ftabset: function(mOptions) {
			
			var options = {
				'style':'default'
			};
			options = $.extend(options, mOptions);
			
			var $this = this;
			$this.addClass("f-tab-container");
			options.style == 'classic' && $this.addClass('f-style-classic');
			var defaultTabData = options.defaultTabData || [];
			var CONTEXT_MENU_DATA = [{
				id:"right_menu_closeCurrent",
				name:"关闭此页"
			}, {
				id:"right_menu_others",
				name:"关闭其它"
			}, {
				id:"right_menu_closeAll",
				name:"关闭所有"
			}, {
				id:"right_menu_refresh",
				name:"刷新"
			}];
			var iframeHeight = options.iframeHeight || "97%"; 
			
			var result = {
				'getFTabset': function() {
					return $this.find(".f-tabset");
				},
				// 获取当前激活的菜单的信息
				'getCurrentMenuInfo': function() {
					// id, url, name
					var $activeTab = $this.find(".f-tabset").find("ul>li.active");
					return {
						'id': $activeTab.data('id'),
						'name': $activeTab.data('name'),
						'url': $activeTab.data('url')
					};
				},
				'activeMenu': function(id, name, url, closeItems){
					// 若存在$parentBody， 激活tab时应该隐藏
					options.$parentBody && options.$parentBody.hide();
					if (id) {
						if (this.activeHistory.size() >= 8) {
							$.messager.info("页面打开失败，你打开的标签数太多，请先关闭一些标签");
							return ;
						}
						// 判断是否存在
						this.activeHistory.put(id);
						var $mItem = this.getFTabset().find('ul>li[data-id="'+ id +'"]');
						this.getFTabset().find("ul>li.active").removeClass("active");
						if ( $mItem.length <= 0) {
							$mItem = buildMenuItem({
								'id': id,
								'name': name,
								'url': url,
								'class': 'active'
							});
							this.getFTabset().find("ul").append($mItem);
						} else {
							$mItem.addClass('active');
						}
					}
					this.refreshFrame(closeItems);
				},
				'closeMenu': function(id) {
					var closeItems = [id];
					this._closeMenu(closeItems);
					var latestTabId = null;
					try {
						latestTabId = this.activeHistory.latest();
					} catch (e){
						
					}
					this.activeMenu(latestTabId, null, null, closeItems); // activeMenu中会对iframe进行操作
					// 判断是否关闭了所有tab（defaultTab除外），当所有tab被关闭时执行
					if (this._allTabIsClosed()) {
						options.$parentBody && options.$parentBody.show();
						options.onAllTabClosed && options.onAllTabClosed();
					}
				},
				'_closeMenu': function(arr) {
					var _this = this;
					var mArr = new Array();
					$.extend(mArr, arr);
					for (var i = 0; i < mArr.length; i++) {
						var item  = mArr[i];
						if (!_this.idInDefaultTabData(item)) {
							_this.getFTabset().find("ul>li[data-id='" + item + "']").remove();
							_this.activeHistory.remove(item, false);
						}
					}
				},
				'idInDefaultTabData': function(id) {
					for (var i = 0; i < defaultTabData.length; i++) {
						if (defaultTabData[i].id == id) {
							return true;
						}
					}
					return false;
				},
				// 除开default tab未被关闭，其它所有tab被关闭时，返回true
				'_allTabIsClosed': function() {
					var history = this.activeHistory.arr;
					if (!history || history.length <= 0) {
						return true;
					}
					for (var i = 0; i < history.length; i++) {
						if (!this.idInDefaultTabData(history[i])) {
							return false;
						}
					}
					return true;
				},
				'closeAll': function(){
					var mArr = [];
					$.extend(mArr, this.activeHistory.arr);
					// 关闭tabset
					this._closeMenu(mArr);
					var latestTabId = null;
					try {
						latestTabId = this.activeHistory.latest();
						this.activeMenu(latestTabId, null, null, mArr);
					} catch (e){
						this.activeMenu(null, null, null, mArr);
					}
					// 当所有tab被关闭时执行
					this.activeHistory.arr.length == 0 && options.$parentBody && options.$parentBody.show();
					options.onAllTabClosed && options.onAllTabClosed();
				},
				'refreshMenus': function(){
					
				},
				// 关闭其它标签，id为不需要关闭的标签
				'closeOthers': function(id){
					var arr = this.activeHistory.except([id]);
					this._closeMenu(arr);
					this.activeMenu(id, arr);
				},
				'activeHistory': new GenericSet(),
				// 隐藏所有项，然后找到tabset中，active那一项，呈现即可
				// @param closeItems:要关闭的项的ID组成的数组
				'refreshFrame': function(closeItems, refresh) {
					var menu = this.getCurrentMenuInfo();
					var $frameSet = $(".f-frame-container");
					if (menu && menu.id) {
						if (StringUtil.isEmpty(menu.url)) {
							menu.url = ctx + '/blank';
						}
						var id = menu['id'];
						var url = menu['url'];
						var name = menu['name'];
						if ($frameSet.length <= 0) {
							$frameSet = $("<div class='f-frame-container'/>");
							$this.append($frameSet);
						}
						$frameSet.find(".f-frame-item").hide();
						var $iframe = $frameSet.find("iframe[data-id='" + id + "']");
						
						if ($iframe.length <= 0) {
							var $mFrame = $("<iframe class='f-frame-item'/>");
							$mFrame.attr({
								'id':id,
								'data-id': id,
								'data-url': url,
								'src': url,
								'data-name': name,
								'frameborder': '0',
								'height': iframeHeight,
								'data-pid': $.getWindowKey()
							});
							$frameSet.append($mFrame);
						}
						
						if (($iframe.length > 0 && $iframe.data("url") != url) || refresh) {
							$iframe.attr("src", url);
						}
						$iframe.show();
					}
					
					// 删除需要删除的iframe
					var _this = this;
					if (closeItems && closeItems instanceof Array && closeItems.length > 0) {
						$.each(closeItems ,function(index,id) {
							if (!_this.idInDefaultTabData(id) ) {
								$frameSet.find("iframe[data-id='" + id + "']").remove();
							}
						});
					}
				}
			};
			
			// 构造右键菜单
			var outputContextMenu = function($underView, data, x, y, defaultTabData, defaultHideKey, onContextMenuClick) {
				if (!$this.$contextmenu) {
					var $div = $("<div/>");
					$div.addClass("m-contextmenu");
					$div.hide();
					var $ul = $("<ul/>");
					$.each(data, function(index, item) {
						var $li = $("<li/>");
						$li.attr({
							'id': item['id']
						});
						$li.text(item['name']);
						$li.on('mouseup', function(e) {
							if (e.button == 0) {
								e.stopPropagation();
								$this.$contextmenu.hide();
							}
						}, false);
						$ul.append($li);
					});
					$div.append($ul);
					$this.$contextmenu = $div;
					$("body").append($this.$contextmenu);
				}
				$this.$contextmenu.find("li").off('click').on('click', function(e){
					onContextMenuClick && onContextMenuClick($(this), $underView);
					$this.$contextmenu.hide();
				});
				$this.$contextmenu.css({
					"left": (x + 1) + "px",
					"top": (y + 1 ) + "px"
				});
				$this.$contextmenu.show();
				$(document).off('mouseup').on('mouseup', function(){
					$this && $this.$contextmenu && $this.$contextmenu.hide();
				} );
				var id = $underView.data("id");
				$this.$contextmenu.find("#right_menu_closeCurrent").toggleClass("disabled", false);
				$.each(defaultTabData, function(index,item){
					if (item.id == id) {
						$this.$contextmenu.find("#right_menu_closeCurrent").toggleClass("disabled", true);
					}
				});
				$this.$contextmenu.find("#right_menu_refresh").toggleClass("disabled", false);
				if (!$underView.hasClass('active')) {
					$this.$contextmenu.find("#right_menu_refresh").toggleClass("disabled", true);
				}
			};
			
			// 右键菜单项被点击时触发的事件
			// $contextMenuItem 上下文菜单项，可以得到其id，
			// $underView 上下文菜单所悬停的tabset item，可以得到data(name,url,id)
			var onContextMenuItemClickFunc = function($contextMenuItem, $underView) {
				var contextMenuItemId = $contextMenuItem.attr("id");
				var id = $underView.data("id");
				if (contextMenuItemId == "right_menu_closeCurrent") {
					// 关闭当前
					result.closeMenu(id);
				} else if (contextMenuItemId == "right_menu_others") {
					// 关闭其它
					result.closeOthers(id);
				} else if (contextMenuItemId == "right_menu_closeAll") {
					// 关闭所有
					result.closeAll();
				} else if (contextMenuItemId == "right_menu_refresh") {
					// 刷新
					result.refreshFrame(null, true);
				}
			};
			
			// 构造tabset item
			var buildMenuItem = function(item) {
				result.activeHistory.put(item['id']);
				var $li = $("<li/>");
				$li.attr({
					"data-id":item['id'],
					'data-name':item['name'],
					'data-url':item['url'],
					'class': 'm-tab'
				});
				$li.toggleClass("active", item['active']);
				$li.off('click').on('click', function(e) {
					e.stopPropagation();
					e.preventDefault();
					options.onSwitch && options.onSwitch(e);
					$this.find(".f-tabset").find("ul").find("li.active").removeClass('active');
					$li.addClass('active');
					result.refreshFrame();
				});
				$li.off('contextmenu').on('contextmenu', function(e){
					e.preventDefault();
					outputContextMenu($(this), CONTEXT_MENU_DATA, e.pageX, e.pageY, defaultTabData,
							"right_menu_closeCurrent",
							onContextMenuItemClickFunc);
					
				});
				var $a = $("<a/>");
				$a.attr({
					"href":item['url'],
					"title":item['name']
				});
				if (!item['defaultItem']) {
					var $i = $("<i class='fa fa-fw fa-times-circle'></i>");
					$i.off('click').on('click', function(e){
						e.stopPropagation();
						e.preventDefault();
						var id = $i.closest("li.m-tab").data('id');
						result.closeMenu(id);
					});
					$a.append($i);
					var $span = $('<span/>');
					$span.html(item['name']);
					$i.after($span);
//					$i.after(item['name']);
				} else {
					var $span = $('<span/>');
					$span.html(item['name']);
					$a.append($span);
//					$a.text(item['name']);
				}
				
				if (options.style == 'classic'){
					var $em = $("<em/>");
					$a.append($em);
				}
				$li.append($a);
				return $li;
			};
			
			var outputMenus = function(data) {
				// 清空内容
				var $tabset = $this.find(".f-tabset");
				$this.find('.error-prompt').remove();
				if ($tabset.length == 0) {
					$tabset = $("<div class='f-tabset'/>");
					var $ul = $("<ul/>");
					$tabset.append($ul);
					$this.append($tabset);
				}
				var $ul = $tabset.find("ul");
				$ul.empty();
				
				options.className && $ul.addClass(options.className);
				if (data && data.length > 0) {
					$.each(data,function(index, item){
						$ul.find("li.active").removeClass('active');
						item['defaultItem'] = true;
						var $item = buildMenuItem(item);
						$ul.append($item);
					});
				}
				$ul.focus();
			};
			
			outputMenus(defaultTabData);
			result.refreshFrame();
			return result;
		}
	});
})(window.jQuery);

